<template>
	<view>

		<view class="chat-box">
			<!-- 聊天记录区域 -->
			<view class="chat-record" ref="chatRecord">
				<view class="chat-item" v-for="(item,index) in chatList">
					<view class="avatar-container" v-if="!item.isSelf">
						<img class="avatar" :src="item.avatar" alt="">
					</view>
					<view class="chat-content-container">
						<view class="nickname-time-container">
							<view class="nickname" v-if="!item.isSelf">{{ item.nickname }}</view>
							<view class="time">{{ item.time }}</view>
							<view class="nickname" v-if="item.isSelf">{{ item.nickname }}</view>
						</view>
						<view class="chat-content-wrapper">
							<view class="chat-content" v-if="item.type === 'text'" v-html="item.content"></view>
							<view class="chat-content" v-else-if="item.type === 'image'">
								<img :src="item.content" alt="">
							</view>
							<u-button type="info" plain @click="copyText(index)" v-if="item.isCopy">COPY
							</u-button>
						</view>
					</view>
					<view class="avatar-container" v-if="item.isSelf">
						<img class="avatar" :src="item.avatar" alt="">
					</view>
				</view>
				<!-- 	<view class="el-backtop" @click="toTop" v-show="showBacktop"
					style="z-index: 999999;width:25px;height:25px;opacity:0.7;position: fixed;right: 50px;bottom: 200px">
					<svg style="width: 15px;height: 15px" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
						<path fill="currentColor" d="M512 320 192 704h639.936z"></path>
					</svg>
				</view> -->
				<!-- <u-button type="error" @click="clear">清空聊天内容</u-button> -->
			</view>
			<!-- 输入框区域 -->
			<view class="chat-input">
				<u--form ref="uForm" size="small" :model="formData" labelPosition="left" labelWidth="70px"
					style="width: 100%;">
					<u-form-item label="消息内容">
						<u--textarea @confirm="sendMessage" placeholder="请输入内容"
							v-model="formData.message"></u--textarea>
					</u-form-item>
					<u-form-item style="float: right">
						<u-button type="primary" @click="sendMessage">发送</u-button>
						<u-button type="info" @click="reset">重置</u-button>
					</u-form-item>
				</u--form>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		chat
	} from "../../api/chatgpt";
	import MarkdownIt from "markdown-it";

	const md = new MarkdownIt();

	export default {
		data() {
			return {
				userinfo: null,
				showBacktop: false,
				wrapStyle: {}, // 滚动容器的样式
				chatNickName: "ChatAI",
				isAnswered: false,
				loading: true,
				chatAvatar: 'https://zlw-blog.oss-cn-hangzhou.aliyuncs.com/2023/05/06/robot.JPEG',
				// userAvatar: this.userinfo.avatar,
				chatContent: '',
				chatList: [
					// 聊天记录列表示例
					{
						id: 2,
						nickname: 'ChatAI',
						avatar: 'https://zlw-blog.oss-cn-hangzhou.aliyuncs.com/2023/05/06/robot.JPEG',
						type: 'text',
						content: 'Hello~我是一名AI语言模型，我能够回答问题、提供建议和信息，和人类进行自然流畅的对话，快来探索吧！',
						time: '00:00',
						isSelf: false,
						isCopy: false
					},
					// ...
				],
				formData: {
					message: '' // 消息内容
				}
			};
		},
		onLoad() {
			this.userinfo = uni.getStorageSync('user-info') || null
			if (this.userinfo == null) {
				uni.showModal({
					title: '系统提示',
					content: '该操作需要登录，点击“登录”跳转到登录页面',
					confirmText: '登录',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							// 跳转登录界面
							uni.reLaunch({
								url: "/pages/user/user"
							});
						}
					}
				});
			}
		},
		// mounted() {
		// 	this.$nextTick(() => {
		// 		this.setShowBacktop();
		// 		this.$refs.chatRecord.addEventListener("scroll", this.setShowBacktop);
		// 	});
		// },
		// beforeUnmount() {
		// 	this.$refs.chatRecord.removeEventListener("scroll", this.setShowBacktop);
		// },
		methods: {
			// toTop() {
			// 	let scrollTop = this.$refs.chatRecord.scrollTop;
			// 	if (scrollTop > 0) {
			// 		const timeTop = setInterval(() => {
			// 				this.$refs.chatRecord.scrollTop = scrollTop -= 50; //一次减50往上滑动
			// 				if (scrollTop <= 0) {
			// 					clearInterval(timeTop);
			// 				}
			// 			},
			// 			10); //定时调用函数使其更顺滑
			// 	}
			// },
			// setShowBacktop() {
			// 	const scrollTop = this.$refs.chatRecord.scrollTop || this.$refs.chatRecord.pageYOffset;
			// 	this.showBacktop = scrollTop > 0;
			// 	console.log(this.showBacktop)
			// },
			clear() {
				if (this.chatList.length === 1) {
					uni.$u.toast("当前没有什么需要清除的，开始你的提问吧~")
				} else {
					uni.showModal({
						title: '系统提示',
						content: '确定要清空所有聊天内容?',
						confirmText: '确定',
						success: function(res) {
							if (res.confirm) {
								this.chatList = [{
									id: 2,
									nickname: 'ChatAI',
									avatar: 'https://zlw-blog.oss-cn-hangzhou.aliyuncs.com/2023/05/06/robot.JPEG',
									type: 'text',
									content: 'Hello~我是一名AI语言模型，我能够回答问题、提供建议和信息，和人类进行自然流畅的对话，快来探索吧！',
									time: '00:00',
									isSelf: false,
									isCopy: false
								}]
								uni.$u.toast("清除成功~")
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			},
			reset() {
				this.formData.message = ''
			},
			copyText(index) {
				uni.setClipboardData({
					data: this.chatList[index].copyContent,
					success: () => {
						uni.showToast({
							title: '复制成功',
							icon: 'success',
							duration: 2000
						});
					},
					fail: () => {
						uni.showToast({
							title: '复制失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			// copyText(index) {
			// 	var textArea = document.createElement("textarea");
			// 	textArea.value = this.chatList[index].copyContent;
			// 	textArea.style.position = "fixed";
			// 	document.body.appendChild(textArea);
			// 	textArea.focus();
			// 	textArea.select();
			// 	const successful = document.execCommand("copy");
			// 	document.body.removeChild(textArea);
			// 	if (successful) {
			// 		uni.$u.toast("复制成功~")
			// 		console.log('文本已复制到剪贴板');
			// 	} else {
			// 		uni.$u.toast("复制失败~")
			// 		console.log("复制失败，可能是浏览器不支持");
			// 	}

			// },
			sendMessage() {
				if (this.formData.message === '' || this.formData.message == null) {
					uni.$u.toast("请输入聊天内容~")
					return
				}
				const avatar = this.userinfo.avatar; // 当前用户的头像
				const nickname = this.userinfo.nickName; // 当前用户的昵称
				const time = new Date().toLocaleTimeString(); // 利用系统当前时间作为发送时间

				const item = {
					id: 1,
					nickname,
					avatar,
					type: 'text',
					content: this.formData.message,
					time,
					isSelf: true,
					isCopy: false
				};

				this.chatList.push(item);
				this.scrollToBottom()

				const waitItem = {
					id: 4,
					nickname: this.chatNickName,
					avatar: this.chatAvatar,
					type: 'text',
					content: "请耐心等待，机器人正在思考中...",
					time: new Date().toLocaleTimeString(),
					isSelf: false,
					isCopy: false
				};
				this.chatList.push(waitItem);
				this.scrollToBottom()
				// 调用api处理提问
				// this.startStreaming(this.formData.message)
				const message = this.formData.message;
				this.formData.message = '';
				chat(message).then((res) => {
					const answerItem = {
						id: this.generateRandomId(),
						nickname: this.chatNickName,
						avatar: this.chatAvatar,
						type: 'text',
						content: md.render(res),
						copyContent: res,
						time: new Date().toLocaleTimeString(),
						isSelf: false,
						isCopy: true
					};
					this.chatList.push(answerItem);
					this.scrollToBottom()
					console.log(answerItem)
				}).catch((res) => {
					let message = "很抱歉，我出现了一些小问题。请多尝试几次或者联系我的主人（499152654@qq.com）进行修复。谢谢您的耐心等待！ (●'◡'●)ﾉ♥\"";
					if (res.toString().includes("Full authentication")) {
						message = "需要先登录我才能回答你的问题哦~"
					}
					const errorItem = {
						id: 2,
						nickname: this.chatNickName,
						avatar: this.chatAvatar,
						type: 'text',
						content: message,
						time: new Date().toLocaleTimeString(),
						isSelf: false,
						isCopy: false
					};
					this.chatList.push(errorItem);
					this.scrollToBottom()
				})
			},
			// 将滚动条滚动到底部
			scrollToBottom() {
				let scrollRef = this.$refs.chatRecord;
				setTimeout(() => {
					// scrollRef.scrollTop = scrollRef.scrollHeight;
					scrollRef.scrollTo({
						top: scrollRef.scrollHeight,
						behavior: 'smooth'
					})
					console.log("scrollTop:" + scrollRef.scrollTop)
				}, 20);
			},
			// 生成随机UUID
			generateRandomId() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			}
		}
	};
</script>

<style scoped>
	.card-header {
		height: 30px;
	}

	.chat-box {
		display: flex;
		flex-direction: column;
		height: 1400rpx;
	}

	.chat-record {
		flex: 1;
		height: 100%;
		overflow-y: auto;
		padding: 10px;
	}

	.chat-item {
		display: flex;
		align-items: flex-end;
		margin-bottom: 20px;
	}

	.avatar-container {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		overflow: hidden;
		margin-right: 10px;
	}

	.avatar {
		width: 100%;
		height: 100%;
	}

	.chat-content-container {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.nickname-time-container {
		display: flex;
		align-items: center;
		margin-bottom: 5px;
	}

	.nickname {
		font-weight: bold;
		margin-right: 10px;
	}

	.time {
		font-size: 12px;
		margin-right: 10px;
	}

	.chat-content-wrapper {
		display: flex;
		align-items: flex-end;
	}

	.chat-content {
		text-align: left;
		padding: 5px 10px;
		border-radius: 10px;
		word-break: break-all;
		margin-right: 10px;
		background-color: #f2f3f5;
		max-width: 95%;
		line-height: 20px;
	}

	.chat-content img {
		max-width: 250px;
		max-height: 250px;
	}

	.chat-content img:hover {
		opacity: 0.8;
	}

	.chat-input {
		padding: 10px;
	}

	.chat-input .el-form-item {
		margin-bottom: 10px;
	}
</style>